package com.example.waterdispenserm2.vmc;

import android.app.Service;
import android.content.Intent;
import android.os.Binder;
import android.os.IBinder;

import com.example.waterdispenserm2.inter.M2InterfaceUtil;
import com.example.waterdispenserm2.util.MyLog;

public class SerialService extends Service {
    private static final String TAG = "SerialService";
    private final IBinder binder = new SerialBinder();
    private SerialPortHelper serialHelper;
    private DataParser.DeviceData deviceData = new DataParser.DeviceData();

    public class SerialBinder extends Binder {
        public SerialService getService() {
            return SerialService.this;
        }
    }

    @Override
    public IBinder onBind(Intent intent) {
        return binder;
    }

    @Override
    public void onCreate() {
        super.onCreate();
            initSerialPort();
    }

    /**
     * 初始化串口
     */
    private void initSerialPort() {
        serialHelper = new SerialPortHelper(new SerialPortHelper.SerialDataListener() {
            @Override
            public void onDataReceived(byte[] data) {
                // 解析数据
                DataParser.DeviceData newData = DataParser.parse(data);
                if (newData != null) {
                    updateDeviceData(newData);
                }
            }

            @Override
            public void onConnectionChanged(boolean connected) {
                // 广播连接状态
                broadcastStatus(connected);
            }
        });
        serialHelper.connect();
    }

    /**
     * 更新设备数据
     * @param newData 新解析的数据
     */
    private void updateDeviceData(DataParser.DeviceData newData) {
        // 根据数据类型合并数据
        switch (newData.dataType) {
            case DataParser.DeviceData.DATA_TYPE_REALTIME:
                // 更新实时数据
                deviceData.currentTemp = newData.currentTemp;
                deviceData.currentVolume = newData.currentVolume;
                deviceData.input1 = newData.input1;
                deviceData.input2 = newData.input2;
                deviceData.input3 = newData.input3;
                deviceData.input4 = newData.input4;
                deviceData.output1 = newData.output1;
                deviceData.output2 = newData.output2;
                deviceData.output3 = newData.output3;
                deviceData.output4 = newData.output4;

                M2InterfaceUtil.doCallBackUpdateUI(deviceData);

                break;

            case DataParser.DeviceData.DATA_TYPE_IO_STATUS:
                // 更新IO状态
                deviceData.input1 = newData.input1;
                deviceData.input2 = newData.input2;
                deviceData.input3 = newData.input3;
                deviceData.input4 = newData.input4;
                deviceData.output1 = newData.output1;
                deviceData.output2 = newData.output2;
                deviceData.output3 = newData.output3;
                deviceData.output4 = newData.output4;
                break;

            case DataParser.DeviceData.DATA_TYPE_SUMMARY:
                // 更新累计数据
                deviceData.totalWater = newData.totalWater;
                deviceData.heatingCount = newData.heatingCount;
                deviceData.workingTime = newData.workingTime;
                break;

            case DataParser.DeviceData.DATA_TYPE_ERROR:
                // 更新错误信息
                deviceData.currentError = newData.currentError;
                deviceData.historyErrors = newData.historyErrors;
                break;

            case DataParser.DeviceData.DATA_TYPE_COMMAND_RESPONSE:
                // 处理指令响应
                MyLog.e(TAG, "Command ACK received: " + newData.commandAck);
                break;
        }

        // 发送广播更新UI
        broadcastDataUpdate();
    }

    /**
     * 广播数据更新
     */
    private void broadcastDataUpdate() {
        Intent intent = new Intent("SERIAL_DATA_UPDATE");
        intent.putExtra("data", deviceData);
        sendBroadcast(intent);
    }

    /**
     * 广播连接状态
     * @param connected 是否已连接
     */
    private void broadcastStatus(boolean connected) {
        Intent intent = new Intent("SERIAL_STATUS_UPDATE");
        intent.putExtra("connected", connected);
        sendBroadcast(intent);
    }

    // ========== 提供给Activity的接口方法 ==========

    /**
     * 发送出水控制指令
     * @param start true:开始出水, false:停止出水
     * @param normal 1是常温否则不是
     * @param temp 温度设置(35-98℃)
     * @param volume 水量设置(30-3000ml)
     */
    public void sendWaterCommand(boolean start, int temp, int volume,int normal) {
        byte[] cmd = CommandBuilder.buildWaterControl(start, temp, volume,normal);
        serialHelper.sendData(cmd);
    }

    /**
     * 发送输出控制指令
     * @param config 输出配置
     */
    public void sendOutputCommand(CommandBuilder.OutputConfig config) {
        byte[] cmd = CommandBuilder.buildOutputControl(config);
        serialHelper.sendData(cmd);
    }

    /**
     * 查询累计数据
     */
    public void querySummaryData() {
        byte[] cmd = CommandBuilder.buildQuerySummary();
        serialHelper.sendData(cmd);
    }

    /**
     * 查询错误信息
     */
    public void queryErrorInfo() {
        byte[] cmd = CommandBuilder.buildQueryError();
        serialHelper.sendData(cmd);
    }

    @Override
    public void onDestroy() {
        if (serialHelper != null) {
            serialHelper.disconnect();
        }
        super.onDestroy();
    }
}